﻿using Microsoft.Web.WebView2.Core;
using MiniExcelLibs;
using System.Data;
using System.Text.Json;
using TikTokApp.Interfaces;
using TikTokApp.Model;
using TikTokApp.Services;

namespace TikTokApp.Pages
{
    public partial class 视频采集 : UserControl, ITabPage
    {
        public 视频采集()
        {
            InitializeComponent();
            ControlHelper.SetControlHeight(this);
            PerformLayout(); // 强制刷新布局
        }
        private async void InitializeWebView(string keyword)
        {

            // 创建自定义环境选项
            var options = new CoreWebView2EnvironmentOptions()
            {
                AdditionalBrowserArguments = "--disable-blink-features=AutomationControlled"
            };

            // 创建环境时传入选项
            var env = await CoreWebView2Environment.CreateAsync(null, null, options);

            // 初始化WebView2
            await webView21.EnsureCoreWebView2Async(env);

            // 3. 修改浏览器指纹
            await DisableAutomationFlags();

            // 移除自动化控制标志
            await webView21.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync(
                "Object.defineProperty(navigator, 'webdriver', { get: () => false });");

            // 设置常见用户代理
            webView21.CoreWebView2.Settings.UserAgent =
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";

            string searchUrl = $"https://www.douyin.com/search/{Uri.EscapeDataString(keyword)}?type=video";
            // 添加随机Referer
            webView21.CoreWebView2.NavigationStarting += (s, e) =>
            {
                e.RequestHeaders.SetHeader("Referer", "https://www.douyin.com/");
            };


            // Navigate to the URL
            webView21.CoreWebView2.Navigate(searchUrl);

            // 等待页面加载完成
            webView21.CoreWebView2.NavigationCompleted += async (s, e) =>
            {
                // 随机延迟2-5秒
                await Task.Delay(2000);
                await ScrollAndExtract();
            };
        }
        private async Task DisableAutomationFlags()
        {
            string script = @"
        // 移除navigator.webdriver标志
        Object.defineProperty(navigator, 'webdriver', {
            get: () => false,
        });
        
        // 修改plugins和languages
        Object.defineProperty(navigator, 'plugins', {
            get: () => [1, 2, 3],
        });
        
        Object.defineProperty(navigator, 'languages', {
            get: () => ['zh-CN', 'zh'],
        });
        
        // 修改屏幕分辨率
        Object.defineProperty(window, 'screen', {
            get: () => ({
                width: 1920,
                height: 1080,
                colorDepth: 24,
                pixelDepth: 24,
                availWidth: 1920,
                availHeight: 1040
            }),
        });
        
        // 修改其他可能被检测的属性
        window.chrome = {
            app: {
                isInstalled: false,
            },
            webstore: {
                onInstallStageChanged: {},
                onDownloadProgress: {},
            },
            runtime: {
                PlatformOs: {
                    MAC: 'mac',
                    WIN: 'win',
                    ANDROID: 'android',
                    CROS: 'cros',
                    LINUX: 'linux',
                    OPENBSD: 'openbsd',
                },
                PlatformArch: {
                    ARM: 'arm',
                    X86_32: 'x86-32',
                    X86_64: 'x86-64',
                },
                PlatformNaclArch: {
                    ARM: 'arm',
                    X86_32: 'x86-32',
                    X86_64: 'x86-64',
                },
                RequestUpdateCheckStatus: {
                    THROTTLED: 'throttled',
                    NO_UPDATE: 'no_update',
                    UPDATE_AVAILABLE: 'update_available',
                },
                OnInstalledReason: {
                    INSTALL: 'install',
                    UPDATE: 'update',
                    CHROME_UPDATE: 'chrome_update',
                    SHARED_MODULE_UPDATE: 'shared_module_update',
                },
                OnRestartRequiredReason: {
                    APP_UPDATE: 'app_update',
                    OS_UPDATE: 'os_update',
                    PERIODIC: 'periodic',
                },
            },
        };
    ";

            await webView21.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync(script);
        }
        async Task<bool> IsEndOfPageAsync()
        {
            // 暂时没有更多了
            var result = await webView21.CoreWebView2.ExecuteScriptAsync(@"
                (function() {
                    let endElement = document.querySelector('.shrAJJLa'); 
                    if (endElement) {
                        return true;
                    }
                    return false;
                })();
            ");
            return bool.Parse(result);
        }

        int currentCount = 0;
        bool isScrolling = true;

        public event EventHandler CloseRequested;

        public string PageTitle => "视频采集";

        public bool AllowClose => true;

        // 自动滚动并提取达人信息
        private async Task ScrollAndExtract()
        {
            // 执行JavaScript模拟人类滚动
            string scrollScript = @"
        // 缓慢滚动到页面底部
        function smoothScroll() {
            return new Promise((resolve) => {
                const totalHeight = document.body.scrollHeight;
                const windowHeight = window.innerHeight;
                const distance = 100; // 每次滚动距离
                const delay = 200; // 滚动间隔时间(ms)
                
                let currentPos = 0;
                
                const scrollInterval = setInterval(() => {
                    window.scrollBy(0, distance);
                    currentPos += distance;
                    
                    // 随机暂停
                    if (Math.random() < 0.3) {
                        clearInterval(scrollInterval);
                        setTimeout(() => {
                            const newInterval = setInterval(() => {
                                window.scrollBy(0, distance);
                                currentPos += distance;
                                
                                if (currentPos >= totalHeight - windowHeight) {
                                    clearInterval(newInterval);
                                    resolve();
                                }
                            }, delay);
                        }, Math.random() * 2000 + 1000); // 随机暂停1-3秒
                    }
                    
                    if (currentPos >= totalHeight - windowHeight) {
                        clearInterval(scrollInterval);
                        resolve();
                    }
                }, delay);
            });
        }
        
        smoothScroll();
    ";
            // Start the loop for scrolling
            while (isScrolling)
            {
                // 检查是否出现 "暂时没有更多了"
                if (await IsEndOfPageAsync())
                {
                    isScrolling = false;
                    AddlistBox1Msg("已滚动到底部，停止采集,正在导出数据");
                    Btn_export_Click(btn_export, EventArgs.Empty); // 直接调用事件方法
                    break;
                }
                // Execute the script to get the current item count
                var countStr = await webView21.CoreWebView2.ExecuteScriptAsync(@"
                    var itemCount = document.querySelectorAll('ul[data-e2e=""scroll-list""] li').length;
                    itemCount;
                ");

                // Convert result to integer
                currentCount = int.Parse(countStr);
                AddlistBox1Msg($"{DateTime.Now}采集到达人数据{currentCount},继续采集中...");

                // Perform scrolling
                // await webView21.CoreWebView2.ExecuteScriptAsync("window.scrollBy(0, 1000);");
                await webView21.CoreWebView2.ExecuteScriptAsync(scrollScript);
                await Task.Delay(new Random().Next(1000, 6000)); // Random delay between scrolls
            }
        }

        // 创建 Excel 文件并保存
        public void ExportToExcel(List<VideoInfo> users, string sheetName)
        {
            if (users == null || users.Count == 0)
            {
                AddlistBox1Msg($"无可导出的达人数据");
                return;
            }

            string timestamp = DateTime.Now.ToString("yyyyMMddHHmmss");
            string fileName = $"{sheetName}_{timestamp}.xlsx";
            string filePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), fileName);

            var data = users.Select(u => new Dictionary<string, object>
            {
                { "账号昵称", u.uname },
                { "视频名称", u.videoname },
                { "视频地址", u.videosrc },
            }).ToList();

            using (var stream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
            {
                MiniExcel.SaveAs(stream, data);
            }
            AddlistBox1Msg($"采集完成，共{users.Count}个达人信息。\n导出文件路径: {filePath}");
        }

        private void SearchButton_Click(object sender, EventArgs e)
        {
            // Get the keyword from the TextBox
            string keyword = searchTextBox.Text.Trim();
            if (string.IsNullOrEmpty(keyword))
            {
                MessageBox.Show("Please enter a keyword.");
                return;
            }

            this.listBox1.Visible = true;
            this.listBox1.Items.Clear();
            this.isScrolling = true;
            InitializeWebView(keyword);
        }

        private async void Btn_export_Click(object sender, EventArgs e)
        {
            // 执行 JavaScript 提取达人信息
            string script = @"
                (function() {
                    let results = [];
                    document.querySelectorAll('ul[data-e2e=""scroll-list""] li').forEach(item => {
                        let user = {
                            videoname: item.querySelector('div.VDYK8Xd7')?.innerText.trim() || '',
                            uname: item.querySelector('div.dW_QmDH1 span span:nth-child(2)').innerText.trim() || '',
                            videosrc: item.querySelector('a[class*=""WHgA""]') ? 'https:' + item.querySelector('a[class*=""WHgA""]').getAttribute('href') : ''
                        };
                        results.push(user);
                    });
                    return results;
                })();
            ";

            var result = await webView21.CoreWebView2.ExecuteScriptAsync(script);
            if (!string.IsNullOrWhiteSpace(result))
            {
                List<VideoInfo> users = JsonSerializer.Deserialize<List<VideoInfo>>(result);
                ExportToExcel(users, searchTextBox.Text.Trim());
                AddlistBox1Msg($"采集完成，共{users.Count}个达人信息。文件已导出在桌面");
            }
        }

        private void Btn_StopScroll_Click(object sender, EventArgs e)
        {
            this.isScrolling = false;
        }

        public void AddlistBox1Msg(string message)
        {
            // 添加新数据
            listBox1.Items.Add(message);
            // 确保最多只保留5条数据
            while (listBox1.Items.Count > 10)
            {
                listBox1.Items.RemoveAt(0); // 移除最早的一条
            }
        }

        public UserControl AsUserControl() => this;

        public void OnPageActivated()
        {
            // 激活时恢复采集状态
        }

        public void OnPageDeactivated()
        {

        }
    }
}
